from flask import Flask, request, jsonify
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from config import configKEY

app = Flask(__name__)
@app.route('/send_email', methods=['GET'])
def handle_post_request():
    # 从请求中获取JSON数据
    data = request.form
    send_qq_mail()
    # 打印接收到的数据（可选，用于调试）
    data = {'message': send_qq_mail(), 'data': data}
    return jsonify(data), 200

def send_qq_mail():
    sender = "573561243@qq.com"
    smtpserver = "smtp.qq.com"
    port = 465
    user = '573561243@qq.com'
    password = configKEY()  # 请确保这是正确的密码或授权码
    subject = '标题'
    content = '这是一个测试邮件'  # 请自行替换成您要发送的邮件内容
    receiver = '2136250988@qq.com'
    msg = MIMEText(content, 'plain', 'utf-8')  # 发送的文本信息
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = sender  # 应该使用 sender 变量，而不是 user（尽管在这里它们是相同的）
    msg['To'] = receiver
    try:
        # smtp = smtplib.SMTP()
        # 在实例化时传入服务器地址和端口号
        smtp = smtplib.SMTP_SSL(smtpserver, port)
        smtp.login(user, password)
        # 注意 receiver 应该是一个列表
        smtp.sendmail(sender, [receiver], msg.as_string())
        smtp.quit()  # 显式关闭连接是一个好习惯
        return ("邮件发送成功！！！")
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")
        return ("Error: 无法发送邮件")


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5050, debug=True)